import time
from threading import Thread
from flask_cors import CORS
from app import create_app
from app.function import check_client_activity
from app.iot_mqtt import mqtt_client
from app.iot_mqtt.iot_config import shadow_query_interval

from app.iot_mqtt.iot_funciton import start_shadow_query_interval

app = create_app()

with app.app_context():
    start_shadow_query_interval()

CORS(app)
app.secret_key = 'your_secret_key_here'  # 用于session加密


def run_flask():
    try:
        app.run(host='0.0.0.0', port=5000, use_reloader=False, debug=False)
    finally:
        # 清理资源
        if mqtt_client:
            mqtt_client.loop_stop()
            mqtt_client.disconnect()
        if shadow_query_interval:
            shadow_query_interval.cancel()


if __name__ == '__main__':
    activity_thread = Thread(target=check_client_activity, daemon=True)
    flask_thread = Thread(target=run_flask, daemon=True)

    activity_thread.start()
    flask_thread.start()

    try:
        # 保持主线程活跃，防止解释器退出
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("收到中断信号，关闭程序...")
    finally:
        # 清理资源
        if mqtt_client:
            mqtt_client.loop_stop()
            mqtt_client.disconnect()
        if shadow_query_interval:
            shadow_query_interval.cancel()
